package middleware

import (
	"smc-admin/models"
	"smc-admin/response"
	"smc-admin/utils"

	"github.com/gin-gonic/gin"
)

func ParseJwt() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("Authorization")

		//解析token
		info, err := utils.ParseJwt(token)

		if err != nil {
			panic(response.Body{
				Msg:  err.Error(),
				Code: response.TOKENERR,
			})
		}

		//查询用户
		userModel := models.User{}
		userModel.ID = info.TokenInfo.ID

		data, res := userModel.Find()

		if res != nil {
			panic(response.Body{
				Msg:  res.Error(),
				Code: response.TOKENERR,
			})
		}
		if len(data) == 0 {
			panic("账号不存在")
		}
		user := data[0]
		if user.Status != models.STATUS {
			panic(response.Body{
				Msg:  "token异常！！！",
				Code: response.TOKENERR,
			})
		}
		//校验用户账号信息
		if user.UpdateTime.Unix() != info.TokenInfo.UpdateTime {
			panic(response.Body{
				Msg:  "账号信息发生变更！！！",
				Code: response.TOKENERR,
			})
		}

		ctx.Set("id", info.TokenInfo.ID)
		ctx.Set("auth", user.Auth)
	}
}
